from typing import Any

from aiogram import types
from aiogram_dialog import DialogManager, StartMode

from src.application.user.exceptions import UserIdAlreadyExist
from src.application.user.service import UserService
from src.presentation.tg_bot.states import AdminSG, ClientSG


async def admin_start(_, widget: Any, dialog_manager: DialogManager):
    """Команда старта для админов"""

    await dialog_manager.start(AdminSG.admin, mode=StartMode.RESET_STACK)


async def user_start(message: types.Message, dialog_manager: DialogManager, user_service: UserService):
    """Команда старта для пользователей"""

    user_id = message.from_user.id
    username = message.from_user.username
    if not username:
        username = message.from_user.first_name

    try:
        await user_service.create_user(tg_id=user_id, username=username)
    except UserIdAlreadyExist:
        pass

    user = await user_service.get_user_by_tg_id(user_tg_id=user_id)

    if user.is_registered:
        await dialog_manager.start(ClientSG.start, mode=StartMode.RESET_STACK)
    else:
        await dialog_manager.start(ClientSG.register, mode=StartMode.RESET_STACK)
